/**
 * Copyright (C) 2013 The yydorid-framework project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.yangying.androidframework.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Locale;
import java.util.Properties;

import net.yangying.androidframework.R;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.graphics.Rect;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.SystemClock;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

/**
 * DeviceUtil 获取设备信息
 * 
 * @author YANGYING
 * 
 * @date 2011-5-16
 */
public class DeviceUtil {
	
	private static final String TAG = DeviceUtil.class.getSimpleName();

	private static final String KERNEL_SOURCE = "/proc/version";
	  
	private static final String BUILD_PROPERTIES_FILE = "/system/build.prop";

	private static final String BASEBAND_VERSION_PROP = "gsm.version.baseband";

	/**
	 * Optional (found on Motorola Milestone)
	 */
	private static final String BASEBAND_CONFIGURATION_VERSION_PROP = "ro.gsm.flexversion";

	private static final String FIRMWARE_CONFIGURATION_VERSION_PROP = "ro.build.config.version";

	private static final String FIRMWARE_BUILD_FINGERPRINT_PROP = "ro.build.fingerprint";

	private static boolean readPropsFromFile = false;

	private static Properties buildProps;
	  
	private static String USER_AGENT = "Mozilla/5.0 (Linux; U; Android %s)AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17";

	public static String getDeviceBrand() {
		return Build.BRAND;
	}

	public static String getDeviceModel() {
		return Build.MODEL;
	}

	public static String getDeviceName() {
		return Build.DEVICE;
	}

	public static String getIMEI(Context paramContext) {
		return ((TelephonyManager) paramContext.getSystemService("phone"))
				.getDeviceId();
	}

	public static String getIMSI(Context paramContext) {
		return ((TelephonyManager) paramContext.getSystemService("phone"))
				.getSubscriberId();
	}

	public static void getScreenRect(Context paramContext, Rect paramRect) {
		Display localDisplay = ((WindowManager) paramContext
				.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
		int i = localDisplay.getWidth();
		int j = localDisplay.getHeight();
		paramRect.set(0, 0, i, j);
	}
	
	public static int getScreenWidth(Context paramContext)
	{
		Display localDisplay = ((WindowManager) paramContext
				.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
		return localDisplay.getWidth();
	}
	
	public static int getScreenHeight(Context paramContext)
	{
		Display localDisplay = ((WindowManager) paramContext
				.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
		return localDisplay.getHeight();
	}

	public static String getUserAgent() {
		return getUserAgent(Locale.getDefault());
	}

	private static String getUserAgent(Locale paramLocale) {
		StringBuffer localStringBuffer = new StringBuffer();
		String str1 = Build.VERSION.RELEASE;
		if (str1.length() > 0) {
			localStringBuffer.append(str1);
			localStringBuffer.append("; ");
			String str2 = paramLocale.getLanguage();
			if (str2 == null)
				localStringBuffer.append("en");
			else {
				String str3 = str2.toLowerCase();
				localStringBuffer.append(str3);
			}
			String str4 = paramLocale.getCountry();
			if (str4 != null) {
				localStringBuffer.append("-");
				String str5 = str4.toLowerCase();
				localStringBuffer.append(str5);
			}
		}

		String str6 = Build.VERSION.CODENAME;
		if ("REL".equals(str6)) {
			String str7 = Build.MODEL;
			if (str7.length() > 0) {
				localStringBuffer.append("; ");
				localStringBuffer.append(str7);
			}
		}
		String str8 = Build.ID;
		if (str8.length() > 0) {
			localStringBuffer.append(" Build/");
			localStringBuffer.append(str8);
		}
		localStringBuffer.append("1.0");

		String str9 = USER_AGENT;
		Object[] arrayOfObject = new Object[1];
		arrayOfObject[0] = localStringBuffer;
		return String.format(str9, arrayOfObject);
	}
	
	/**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */ 
    public static int dip2px(Context context, float dpValue) { 
        final float scale = context.getResources().getDisplayMetrics().density; 
        return (int) (dpValue * scale + 0.5f); 
    } 
 
    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */ 
    public static int px2dip(Context context, float pxValue) { 
        final float scale = context.getResources().getDisplayMetrics().density; 
        return (int) (pxValue / scale + 0.5f); 
    } 

//    /**
//     * 获得rom memory
//     * @return
//     */
//    public static long[] getRomMemroy() {
//		long[] romInfo = new long[2];
//		//Total rom memory
//		romInfo[0] = getTotalInternalMemorySize();
//
//		//Available rom memory
//		File path = Environment.getDataDirectory();
//		StatFs stat = new StatFs(path.getPath());
//		long blockSize = stat.getBlockSize();
//		long availableBlocks = stat.getAvailableBlocks();
//		romInfo[1] = blockSize * availableBlocks;
//		return romInfo;
//	}
    
    /*
     * 获取可用rom大小
     */
	public static String getROMAvailable(Context context) {
		File path = Environment.getDataDirectory();
		StatFs stat = new StatFs(path.getPath());
		long blockSize = stat.getBlockSize();
		long availableBlocks = stat.getAvailableBlocks();
		String avail_rom = Formatter.formatFileSize(context, blockSize
				* availableBlocks);
		return avail_rom;
	}

     /*
     * 获取rom总大小
     */
	public static String getROMTotal(Context context) {
		File path = Environment.getDataDirectory();
		StatFs stat = new StatFs(path.getPath());
		long blockSize = stat.getBlockSize();
		long totalBlocks = stat.getBlockCount();
		String total_rom = Formatter.formatFileSize(context, blockSize
				* totalBlocks);
		return total_rom;
	}

//	public static long getTotalInternalMemorySize() {
//		File path = Environment.getDataDirectory();
//		StatFs stat = new StatFs(path.getPath());
//		long blockSize = stat.getBlockSize();
//		long totalBlocks = stat.getBlockCount();
//		return totalBlocks * blockSize;
//	}

//    public static long[] getSDCardMemory() {
//		long[] sdCardInfo=new long[2];
//		String state = Environment.getExternalStorageState();
//		if (Environment.MEDIA_MOUNTED.equals(state)) {
//			File sdcardDir = Environment.getExternalStorageDirectory();
//			StatFs sf = new StatFs(sdcardDir.getPath());
//			long bSize = sf.getBlockSize();
//			long bCount = sf.getBlockCount();
//			long availBlocks = sf.getAvailableBlocks();
//
//			sdCardInfo[0] = bSize * bCount;//总大小
//			sdCardInfo[1] = bSize * availBlocks;//可用大小
//		}
//		return sdCardInfo;
//	}
    
    /*
     * 判断SD卡是否存在
     */
     public boolean isExistSdcard() {
         
        return Environment.getExternalStorageState()
        .equals(Environment.MEDIA_MOUNTED);   
    }
     /*
       * 获取SD卡总大小
       */
     public static String getSdcardTotalSize(Context context) {   
       
        File path = Environment.getExternalStorageDirectory();   
        StatFs stat = new StatFs(path.getPath());   
        long blockSize = stat.getBlockSize();   
        long totalBlocks = stat.getBlockCount();
        String total_result = Formatter.formatFileSize(context, blockSize*totalBlocks);
        return total_result;   
    }  
     /*
     * 获取SD卡可用大小
     */
     public static String getSdcardAvailableSize(Context context){
         
          File path = Environment.getExternalStorageDirectory();   
        StatFs stat = new StatFs(path.getPath());   
        long blockSize = stat.getBlockSize();   
        long availableBlocks = stat.getAvailableBlocks();
        String available_result = Formatter.formatFileSize(context, blockSize*availableBlocks);
        return available_result;
     }
    

    /**
     * CPU信息
     * @return
     */
	public static String[] getCpuInfo() {
		String str1 = "/proc/cpuinfo";
		String str2="";
		String[] cpuInfo={"",""};
		String[] arrayOfString;
		try {
			FileReader fr = new FileReader(str1);
			BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
			str2 = localBufferedReader.readLine();
			arrayOfString = str2.split("\\s+");
			for (int i = 2; i < arrayOfString.length; i++) {
				cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";
			}
			str2 = localBufferedReader.readLine();
			arrayOfString = str2.split("\\s+");
			cpuInfo[1] += arrayOfString[2];
			localBufferedReader.close();
		} catch (IOException e) {
		}
		return cpuInfo;
	}

	/**
	 * baseband
	 * @return
	 */
	public static String getBasebandVersion(){
		String value = Constant.UNKNOWN;
	    try {
	        value = getSystemProperty(BASEBAND_VERSION_PROP);
	        if(value != null && value.length() > 0) 
	        	return value; 
	      } catch (Throwable t) {
	        Log.e(TAG, "Error reading baseband version: "+t.getMessage(), t);
	      }
		return Constant.UNKNOWN;
	}
	private static String getSystemProperty(String propKey) {
		String value = null;
		if (readPropsFromFile) {
			if (buildProps == null) {
				buildProps = new Properties();
				try {
					buildProps.load(new FileInputStream(BUILD_PROPERTIES_FILE));
				} catch (IOException e) {
					Log.e(TAG, "Could not read build.prop file !", e);
				}
			}
			value = buildProps.getProperty(propKey);
		} else {
			try {
				Class sysPropClass = Class
						.forName("android.os.SystemProperties");
				Method getMethod = sysPropClass.getMethod("get", String.class);
				value = (String) getMethod.invoke(sysPropClass.newInstance(),
						propKey);
			} catch (Exception e) {
				Log.e(TAG, "Could not get systemProperty : " + propKey, e);
			}
		}
		Log.e(TAG, "system prop  " + propKey + " = " + value);
		return value;
	}
	/**
	 * 获得os系统版本
	 * @return
	 */
	public static String getOsBuildVersion(){
		return android.os.Build.VERSION.RELEASE;
	}
	/**
	 * 系统版本
	 * Linux version 3.0.8-g54d09f2 (blinky-ghost@cyanogenmod) (gcc version 4.4.3 (GCC) ) #1 PREEMPT Fri Aug 10 00:17:53 PDT 2012
	 * @return
	 */
	public static String[] getKernelVersion(){
		String[] version={"null","null","null","null"};
		String str1 = "/proc/version";
		String str2;
		String[] arrayOfString;
		try {
			FileReader localFileReader = new FileReader(str1);
			BufferedReader localBufferedReader = new BufferedReader(
					localFileReader, 8192);
			str2 = localBufferedReader.readLine();
			arrayOfString = str2.split("\\s+");
			version[0]=arrayOfString[2];//KernelVersion
			localBufferedReader.close();
		} catch (IOException e) {
		}
		version[1] = Build.VERSION.RELEASE;// firmware version
		version[2]=Build.MODEL;//model
		version[3]=Build.DISPLAY;//system version
		return version;
	}

	/**
	 * 获得wifi mac 地址
	 * @return
	 */
	public static String getWifiMacInfo(Context context){
		String addr="null";
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if(wifiInfo.getMacAddress()!=null){
        	addr=wifiInfo.getMacAddress();
		} else {
			addr = "Fail";
		}
        return addr;
	}
	/**
	 * 获得系统启动时间
	 * @param context
	 * @return
	 */
	public static String getSystemUpTimes(Context context) {
		long ut = SystemClock.elapsedRealtime() / 1000;
		if (ut == 0) {
			ut = 1;
		}
		int m = (int) ((ut / 60) % 60);
		int h = (int) ((ut / 3600));
		return h + " " + context.getString(R.string.info_times_hour) + m + " "
				+ context.getString(R.string.info_times_minute);
	}

	/*
     * 获取内存总大小
     */
     public static String getRAMTotalMemory(Context context) {

          String file_path = "/proc/meminfo";// 系统内存信息文件
          String ram_info;
          String[] arrayOfRam;
          long initial_memory = 0;
          try {
               FileReader fr = new FileReader(file_path);
               BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
               // 读取meminfo第一行，系统总内存大小
               ram_info = localBufferedReader.readLine();
               arrayOfRam = ram_info.split("\\s+");//实现多个空格切割的效果
               initial_memory = Integer.valueOf(arrayOfRam[1]).intValue() * 1024;// 获得系统总内存，单位是KB，乘以1024转换为Byte
               localBufferedReader.close();
          }
          catch (IOException e) {
          }
          return Formatter.formatFileSize(context, initial_memory);// Byte转换为KB或者MB，内存大小
     }
     /*
     * 获取内存可用大小
     */
     public static String getRAMAvailMemory(Context context) {// 获取android当前可用内存大小

          ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
          MemoryInfo mi = new MemoryInfo();
          am.getMemoryInfo(mi);// mi.availMem; 当前系统的可用内存
          return Formatter.formatFileSize(context, mi.availMem);// 将获取的内存大小规格化
     }


}
